/*
 * RSS2HTML - Updates a tab from a rss feed to html
 * Version: 0.2.1
 * Author: David Laurell <david.laurell@gmail.com>
 * License: GPLv3
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function query( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function loadFeed() {
   var feedUrl = decodeURIComponent(query('url'));
   var xhr = new XMLHttpRequest();
   xhr.open("GET", feedUrl, true);
   xhr.onreadystatechange = function() {
   if (this.readyState == 4) {
      var xmlparse = this.responseXML;

      if (xhr.status == 200) {
            var description="", items = [];

            var title = xmlparse.getElementsByTagName('title')[0].childNodes[0].nodeValue;

            if(xhr.getResponseHeader("Content-Type").indexOf("application/rss+xml") != -1 ||
                  (xhr.getResponseHeader("Content-Type").indexOf("text/xml") != -1 && xmlparse.getElementsByTagName('rss')[0])) {
               try {
	               description = xmlparse.getElementsByTagName('description')[0].childNodes[0].nodeValue;
               } catch(ex){}

               var xmlItems = xmlparse.getElementsByTagName("item");

               for (var i = 0, xmlItem; xmlItem = xmlItems[i]; i++) {
                  items.push({
	                  title: xmlItem.getElementsByTagName('title')[0].childNodes[0].nodeValue,
	                  description: xmlItem.getElementsByTagName('description')[0].childNodes[0].nodeValue,
	                  url: xmlItem.getElementsByTagName('link')[0].childNodes[0].nodeValue,
	                  time: xmlItem.getElementsByTagName('pubDate')[0].childNodes[0].nodeValue
                  });
               }
            }
            else if(xhr.getResponseHeader("Content-Type").indexOf("application/atom+xml") != -1 ||
                     (xhr.getResponseHeader("Content-Type").indexOf("text/xml") != -1 && xmlparse.getElementsByTagName('feed')[0])) {
               try {
	               description = xmlparse.getElementsByTagName('subtitle')[0].childNodes[0].nodeValue;
               } catch(ex){}

               var xmlItems = xmlparse.getElementsByTagName("entry");

               for (var i = 0, xmlItem; xmlItem = xmlItems[i]; i++) {
                  var summary = "", link = "";

                  try {
                     summary = xmlItem.getElementsByTagName('content')[0].childNodes[0].nodeValue;
                  }
                  catch(ex) {
                     try {
                        summary = xmlItem.getElementsByTagName('summary')[0].childNodes[0].nodeValue;
                     }
                     catch(ex2) {}
                  }

                  try {
                     link = xmlItem.getElementsByTagName('link')[0].childNodes[0].nodeValue;
                  }
                  catch(ex) {}

                  items.push({
	                  title: xmlItem.getElementsByTagName('title')[0].childNodes[0].nodeValue,
	                  description: summary,
	                  url: link,
	                  time: xmlItem.getElementsByTagName('updated')[0].childNodes[0].nodeValue
                  });
               }               
            }
            drawFeeds(title, description, items, feedUrl);
         }
         else {
		      var wrapperNode = document.getElementById('wrapper');
		      wrapperNode.innerHTML = '<h1>Feed not found!</h1><p>The feed with URL "' + feedUrl + '" could not be found</p>';
		      document.title = 'RSS2HTML';
         }
      }
   };
   xhr.send(null);
}

function drawFeeds(title, description, items, feedUrl) {
	document.title = title;

	var wrapperNode = document.getElementById('wrapper');
	wrapperNode.innerHTML = '';

	var button = document.createElement('input');
	button.setAttribute("type","button");
	button.onclick = function() {
		document.location = "http://fusion.google.com/add?feedurl=" + feedUrl;
	};
	button.value = "Subscribe using Google";
	wrapperNode.appendChild(button);

	var h1 = document.createElement('h1');
   var sourceLink = document.createElement('a');
   sourceLink.innerHTML = 'Viewing feed: ' + title;
   sourceLink.href = feedUrl;
   sourceLink.onclick = function(e) {
      e.preventDefault();
      return false;
   };
   h1.appendChild(sourceLink);
	wrapperNode.appendChild(h1);

	var feedDesc = document.createElement('p');
	feedDesc.innerHTML = description;
	wrapperNode.appendChild(feedDesc);

   var htmlItems = [];

	for (var i = 0, item; item = items[i]; i++) {
		var divItem = document.createElement("div");
		divItem.className = "item";

		var time = document.createElement("div");
		time.className = "time";
		time.innerHTML = item.time;
		divItem.appendChild(time);

		var h2 = document.createElement("h2");

		var link = document.createElement("a");
		link.href = item.url;
		link.innerHTML = item.title;
		h2.appendChild(link);

		divItem.appendChild(h2);

		var desc = document.createElement("div");
		desc.className = "content";
		divItem.appendChild(desc);
	
		wrapperNode.appendChild(divItem);

      htmlItems.push(divItem);
	}

   for (var i = 0, htmlItem; htmlItem = htmlItems[i]; i++) {
      var desc = htmlItem.getElementsByClassName("content")[0];
      desc.innerHTML = items[i].description;
   }
}
